<?php
namespace app\controllers;

use app\models\Mobile;
use app\models\MobileBorrow;
use mvc\web\Controller;

class PublicController extends Controller
{
    public function actionSelectModels()
    {
        $os = isset($_GET['os']) ? $_GET['os'] : null;

        $where = '1=1';
        $os && $where .= " and os=$os";

        $model = new Mobile();
        $data = $model->where($where)->groupBy('models')->all();
 
        $this->jsonResponse(['status' => 1, 'data' => $data]);
    }

    public function actionSelectMobiles()
    {
        $os = isset($_GET['os']) ? $_GET['os'] : null;
        $models = isset($_GET['models']) ? $_GET['models'] : null;
        $type = isset($_GET['type']) ? $_GET['type'] : 1;
        $user = isset($_GET['user']) ? $_GET['user'] : '';

        $model = new Mobile();

        $where = "mobile.status=$type";
        $os && $where .= " and os=$os";
        $models && $where .= " and models='$models'";
        if ($type == 2 && !empty($user)) {
            $where .= " and mobile_borrow.borrow_user='$user'";
            $model
                ->select('mobile.*,mobile_borrow.should_return_time')
                ->join(MobileBorrow::tableName(), "on mobile.id=mobile_borrow.mobile_id");
        }

        $data = $model->where($where)->all();

        $this->jsonResponse(['status' => 1, 'data' => $data]);
    }

    public function actionSelectMobileId()
    {
        $user = isset($_GET['user']) ? $_GET['user'] : '';
        $mobileId = isset($_GET['mobileId']) ? $_GET['mobileId'] : '';

        $model = new MobileBorrow();
        $one = $model->where("borrow_user='$user' and mobile_id=$mobileId and status=0")->one();

        if(empty($one)) {
            $this->jsonResponse(['status' => 0, 'msg' => '您没有借用此手机哦~']);
        }

        $isExpire = 0;
        if(strtotime($one['should_return_time'] . ' 23:59:59') < time()) {
            $isExpire = 1;
        }

        $this->jsonResponse(['status' => 1, 'isExpire' => $isExpire, 'shouldReturnTime' => $one['should_return_time'], 'id' => $one['id']]);
    }
}